package net.ideapad.struts.form;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.ideapad.data.Group;
import net.ideapad.hibernate.HibernateSessionFactory;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.hibernate.Session;

/**
 * JavaBean for storing the user input for creating a new group.
 * 
 * MyEclipse Struts Creation date: 12-14-2009
 * 
 * XDoclet definition:
 * 
 * @struts.form name="createGroupForm"
 */
public class CreateGroupForm extends ActionForm {
	// Fields
	private String groupName;
	private Integer parentGroupID;

	// Getters and setters
	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}

	public Integer getParentGroupID() {
		return parentGroupID;
	}

	public void setParentGroupID(Integer parentGroupID) {
		this.parentGroupID = parentGroupID;
	}

	/**
	 * Validate method.  Makes sure that the values set in this bean do not conflict with constraints
	 */
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();

		List<String> errors = new ArrayList<String>();

		//Checks about the parent group.
		if (parentGroupID != null && parentGroupID != 0) {
			Integer userID = (Integer) request.getSession().getAttribute("userID");

			Session session = HibernateSessionFactory.getSession();
			session.beginTransaction();

			Group g = (Group) session.createQuery("from Group g where g.groupId = :id").setInteger("id", parentGroupID).uniqueResult();

			//Parent group not found means print errors.
			if (g != null) {
				Group result = (Group) session.createQuery("from Group g left join fetch g.moderators as m where g.groupId = :groupID AND m.userId = :userID").setInteger("groupID", parentGroupID).setInteger("userID", userID).uniqueResult();

				//The user is not the moderator of the parent group.
				if (result == null) {
					actionErrors.add("Errors", new ActionMessage("You are not a moderator of the group"));
					errors.add("You are not a moderator of the group");
				}

				session.getTransaction().commit();
			} else {
				actionErrors.add("Errors", new ActionMessage("Invalid parent group"));
				errors.add("Invalid parent group");
			}

			HibernateSessionFactory.closeSession();
		}

		//Invalid group names
		if (groupName == null || groupName.equals("")) {
			actionErrors.add("Errors", new ActionMessage("No group name"));
			errors.add("No group name");
		}

		//Set the Errors attribute if errors exist.
		if (errors.size() > 0) {
			request.setAttribute("Errors", errors);
		}

		return actionErrors;
	}
}